import React from 'react'
import {Row, Col, Button, Table, Select, Input, Avatar, Modal, message, Checkbox, Switch, Form, Card} from 'antd'
import './styles.css'
import api from "../../api/api";
import axios from 'axios';
import Model from "./Model";
import Detail from "./Detail"
import {LeftOutlined} from "@ant-design/icons";
const FormItem = Form.Item;


const {Search} = Input;
const {Option} = Select;


class Employee extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增人员",
                visible: false,
                type: 1,//新增人员:1,添加 2,编辑
                gridList: {},

            },
            title: "人员管理",
            visibleForState: false,
            visibleForUser: false,
            data: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            selectedRowIds: [],
            setIdentify: "1",
            hiddenFlag: true,
            uName:"",
            uPwd:"",
            detailHidden: true,
        };
    }
    componentDidMount() {
        this.getUserInfoList();//查询全部
    }
    columns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
            className: "elementHidden",
            width: '1px'
        },
        {
            title: '姓名',
            dataIndex: 'uinfoName',
            //className: "elementHidden",
            key: 'uinfoName',
            width: '15px'
        },
        {
            title: '性别',
            dataIndex: 'uinfoGender',
            key: 'uinfoGender',
            width: '10px'
        },
        {
            title: '身份证号',
            dataIndex: 'uinfoIdcard',
            width: '15px',
            key: 'uinfoIdcard'
        },
        {
            title: '手机号',
            dataIndex: 'uinfoPhone',
            width: '15px',
            key: 'uinfoPhone'
        },
        {
            title: '邮箱',
            dataIndex: 'uinfoEmail',
            width: '15px',
            key: 'uinfoEmail'
        },
        {
            title: '用户账号id',
            dataIndex: 'userinfoId',
            className: "elementHidden",
            width: '15px',
            key: 'userinfoId'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: '15px',
            key: 'createTime'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            width: '15px',
            key: 'updateTime'
        },
        {
            title: '禁用',
            dataIndex: 'isUsed',
            className: "elementHidden",
            width: '15px',
            key: 'isUsed'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '15px',
            key: 'option',
            render: (_ext, record, Item) => {
                    return (
                        <span>
                       <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
                       <a className="optionMargin" onClick={() => this.onClickDelete(record.id)}>删除</a>
                       <a className="optionMargin" onClick={() => this.onClickDetail(record)}>查看详情</a>
                       <Switch checkedChildren="禁用" unCheckedChildren="启用" checked={record.isUsed === 1 ? true:false} onClick={() => this.selectSwitch(record)}  />
                    </span>
                    )
            }
        }
    ];

    getUserInfoList(){
        let that = this;
        axios.post(api.api_URL+"/employee/selectAllUserInfoMeassage?pageNum="+this.state.pageNum+" &pageSize="+
            this.state.pageSize,{
                "uinfoName":this.state.uinfoName
            },
            {
                header:{
                    "Content_Type":api.ContentType
                }
            }).then(function (res) {
            console.info(res.data)
                if(res.data.errorCode != 1){
                    return;
                }
                let totalSize = res.data.object.total;
                const dataList = [];
                for(let i = 0;i < res.data.object.records.length;i++){
                    let resContent = res.data.object.records[i];
                     let content = {};
                     content.key=(i+1);
                     content.id=resContent.id;
                     content.uinfoName=resContent.uinfoName;
                     content.uinfoGender=resContent.uinfoGender;
                     content.uinfoIdcard=resContent.uinfoIdcard;
                     content.uinfoPhone=resContent.uinfoPhone;
                     content.uinfoEmail=resContent.uinfoEmail;
                     content.userinfoId=resContent.userinfoId;
                     content.createTime=resContent.createTime;
                     content.updateTime=resContent.updateTime;
                     content.isUsed =resContent.isUsed;
                     dataList[i] = content;
            }

                that.setState({
                    data: dataList,
                    total: totalSize,
                })
        }).catch(function (err) {
            console.log(err);
        });
    }
    //查看详情
    onClickDetail(item) {
        console.info("查看详情===", item);
        this.setState({
            detailHidden: false
        })
        this.detail.getMeassage(item);
    }

    returnMain = e => {
        this.setState({
            detailHidden: true
        })
    }
//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getUserInfoList()
        });

    }

    refresh() {
        this.getUserInfoList()
    }

    onRef = (ref) => {
        this.child = ref

    }

    onRef2=(name,ref) => {
        switch (name) {
        case 'EmployeeDetail':
            this.detail = ref
            break
        }
    }

    //删除
    onClickDelete(item) {
        let that = this;
        console.info(item);
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/employee/deleteUserInfoById?id="+item;
                    axios.post(url, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        console.log(res.data.errorCode)
                        if (res.data.errorCode != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})
                        that.setState({
                            data: []
                        })
                        that.getUserInfoList();
                        configModel.destroy();

                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})
                        console.log(err);
                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }

    //编辑
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item,

            }
        }, () => {
            this.child.initEditData()
        });
    }
    //设置/修改登陆账号
    addUserPassword(){
        console.log("this.state.selectedRowIds",this.state.selectedRowIds)
        if (this.state.selectedRowIds == null || this.state.selectedRowIds.length == 0){
            message.error({content:"请选择需要设置的行"})
            return;
        }
        if(this.state.selectedRowIds.length!=1){
            message.error({content:"一次只能选择一个人"})
            return;
        }

        this.setState({
            visibleForUser: true
        });
    }
    //添加
    addPersion() {
        this.setState({
            modelData: {
                title: "新增人员",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    //批量删除
    deleteByBatchIds(){
        let that = this;
        if (this.state.selectedRowIds == null || this.state.selectedRowIds.length == 0){
            message.error({content:"请选择需要设置的行"})
            return;
        }
        let configModel = Modal.confirm({
            title: '批量删除',
            content: '是否确认删除这几条数据？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/employee/deleteUserInfoByBatchIds";
                    axios.post(url, {
                        "id":this.state.selectedRowIds,
                    },{
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        console.log(res)
                        if (res.data.errorCode != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})
                        that.setState({
                            data: []
                        })
                        that.getUserInfoList();
                        configModel.destroy();

                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})
                        console.log(err);
                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }



    //单行启用禁用
    selectSwitch(item){
        let that = this;
        if(item.isUsed===0){
            item.isUsed=1
        }else if(item.isUsed===1) {
            item.isUsed=0
        }
        console.log(item)

        this.setState({
            param:{
                id:item.id,
                isUsed:item.isUsed
            }
        },()=> {
            this.selectAwitchdo();
        });

    }
    //单行启用禁用请求
    selectAwitchdo(){
        console.log(this.state.param);
        let that=this;
        axios({
            method: 'POST',
            url: api.api_URL + "/employee/updateIsUseByUserinfoId",
            data: JSON.stringify(this.state.param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            if (response.data.errorCode != 1) {
                message.error({content: "失败，请重新尝试 ！"})
                return;
            }
            message.success({content: "成功！"})
            that.refresh()
        })
            .catch(function (error) {
                message.error({content: "失败，请重新尝试 ！"})
                console.log(error);
            })
    }

    //多行启用
    onclickSetIdentify(){
        console.log("this.state.selectedRowIds",this.state.selectedRowIds)
        if (this.state.selectedRowIds == null || this.state.selectedRowIds.length == 0){
            message.error({content:"请选择需要设置的行"})
            return;
        }
        this.setState({
            visibleForState: true,
        })
    }

    //设置状态的改变事件
    identifyChange=(value)=>{
        console.log(value)
        this.setState({
            isUsed: value,
        })
    }

    //重置内容
    onclickReset() {
        this.setState({
            uinfoName:undefined,
        },() => {
            this.getUserInfoList()
        });
    };
    //设置启用状态确认
    handleOkForIdentify= e =>{
        let that=this;
        let url = api.api_URL + "/employee/updateIsUseByUinfoIds";
        axios.post(url, {
            "id":this.state.selectedRowIds,
            "isUsed":this.state.isUsed
        },{
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            that.handleCancel()
            if (res.data.errorCode==1) {
                message.success({content:"状态设置成功！"})
            }else{
                message.error({content:"状态设置失败！"})
            }
        }).catch(function (err) {
            console.log(err);
        });
        that.setState({
            hiddenFlag:true,
            isUsed:undefined,
        })

    }

    //获取设置的用户名
    getusername(e){
        console.log(e.target.value)
        this.setState({
            uName:e.target.value,
            param:{
                username:e.target.value
            }
        })
    }

    //获取设置的密码
    getpassword=(e)=>{
        console.log(e.target.value)
        this.setState({
            uPwd:e.target.value,
            param:{
                userpassword:e.target.value
            }
        })
    }
    //设置用户名密码确认
    handleOkForUser= e =>{
        console.log(this.state.selectedRowIds)
        console.log(this.state.uName)
        console.log(this.state.uPwd)
        let that=this;
        let url = api.api_URL + "/employee/registerUNameAndUPwdForEmployee?id="+this.state.selectedRowIds;
        axios.post(url, {
            //id是userInfo的id
            "uName":this.state.uName,
            "uPwd":this.state.uPwd
        },{
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            that.handleCancel()
            if (res.data.errorCode==1) {
                message.success({content:"用户名密码设置成功！"})
            }else{
                message.error({content:"用户名密码设置失败！"})
            }
        }).catch(function (err) {
            console.log(err);
        });


    }
    //取消
    handleCancel = e => {
        this.setState({
            visibleForState: false,
            visibleForUser:false,
            isUsed:undefined,
            hiddenFlag: true,
            selectedRowIds: [],
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });
    }
    //搜索员工姓名
    inputChange = (e) => {
        console.log(e.target.value)
        this.setState({
            uinfoName: e.target.value
        })
    }

    onclickSearch()
    {
        console.info("搜索");
        this.getUserInfoList();
    }

    //设置启用状态
    onclickSetIdentify(){
        console.log("this.state.selectedRowIds",this.state.selectedRowIds)
        if (this.state.selectedRowIds == null || this.state.selectedRowIds.length == 0){
            message.error({content:"请选择需要设置的行"})
            return;
        }
        this.setState({
            visibleForState: true,
        })
    }

    render() {
        const {selectedRowKeys } = this.state;
        const CheckboxGroup = Checkbox.Group;
        const CheckBox=Checkbox;
        const rowSelection = {
            columnWidth:10,
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowIds : selectedRowKeys.map(Number),
                    selectedRowKeys
                })
                console.log(`selectedRowKeys: ${selectedRowKeys}`);
                console.log(this.state.selectedRowIds)
            },
        };
        return (

            <div className="girdBg">
                <div className={this.state.detailHidden === true ? "elementShow" : "elementHidden"}>
                    <Row className="searchBox" >
                        <Col span={8} style={{marginTop:15}}>
                            <Search style={{width: 230,marginLeft:30}}
                                    placeholder="请输入员工姓名" onChange={this.inputChange}  allowClear value={this.state.uinfoName}
                            />
                            <Button icon={"search"} type='primary' style={{marginLeft: 30,marginTop:15}}
                                    onClick={this.onclickSearch.bind(this)}>搜索员工</Button>
                            <Button icon={"reset"} style={{marginLeft: 50,marginTop:15}} onClick={this.onclickReset.bind(this)}>重置</Button>
                        </Col>
                        <Col span={16} className="btnRight" style={{marginTop:65}}>
                            <Button icon={"save"} type='primary' onClick={this.addUserPassword.bind(this)}>设置/修改登陆账号</Button>
                            <Button icon={"save"} type='primary' style={{marginLeft: 30}} onClick={this.addPersion.bind(this)}>新增员工</Button>
                            <Button icon={"save"} type='primary'style={{marginLeft: 30}} onClick={this.deleteByBatchIds.bind(this)}>批量删除</Button>
                            <Button icon={"setting"} type='primary' style={{marginLeft: 30,marginRight:30}} onClick={this.onclickSetIdentify.bind(this)}>设置启用状态</Button> {/*    <Button icon={"setting"} type='primary' style={{marginLeft: 30}} onClick={this.onclickSetIdentify.bind(this)}>设置启用状态</Button>*/}
                        </Col>
                    </Row>
                    <Row style={{margin: 30}}>
                        <Table
                            columns={this.columns}
                            dataSource={this.state.data}
                            scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                            rowSelection={rowSelection}
                            rowKey={record =>record.id}
                            columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                                const fun = () => ({style: {whiteSpace: 'nowrap'}});
                                item.onHeaderCell = fun;
                                item.onCell = fun;
                                return item;
                            })}
                            pagination={{
                                simple: false,
                                current: this.state.pageNum,
                                total: this.state.total,
                                pageSize: this.state.pageSize,
                                showTotal: (count = this.state.total) => {
                                    return '共' + count + '条'
                                },
                                onChange: (current, pageSize) => {
                                    this.onBaseClick(current, pageSize)
                                }
                            }}
                        />
                    </Row>
                    {/*添加编辑的model*/}
                    <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                           onRef={this.onRef} history={this.props.history}/>
                    {/*设置状态信息的model*/}
                    <Modal title="设置状态信息"refresh={this.refresh}
                           visible={this.state.visibleForState}
                           onOk={this.handleOkForIdentify}
                           onCancel={this.handleCancel}
                    >
                        <Select style={{width: 300}} placeholder="请选择状态"  onChange={this.identifyChange} value={this.state.isUsed}>
                            <Option key="1">启用</Option>
                            <Option key="0">禁用</Option>
                        </Select>
                    </Modal>
                    {/*设置/登陆账户密码的model*/}
                    <Modal title="设置/登陆账户密码"refresh={this.refresh}
                           visible={this.state.visibleForUser}
                           onOk={this.handleOkForUser}
                           onCancel={this.handleCancel}
                    >
                        <Form name="control-ref"
                              layout="horizontal"
                        >
                            <FormItem  label="用户名" name="username"  allowClear >
                                    <Input
                                        maxLength={32}
                                        placeholder="请输入用户名"
                                        onChange={(e)=>this.getusername(e)}

                                    />
                            </FormItem>
                            <FormItem  label="密码" name="password"  allowClear >
                                    <Input
                                        maxLength={32}
                                        placeholder="请输入密码"
                                        onChange={this.getpassword}
                                    />
                            </FormItem>

                        </Form>
                    </Modal>
              </div>
                <div className={this.state.detailHidden === true ? "elementHidden" : "elementShow"}>
                    <Detail returnMain={this.returnMain} onRef2={this.onRef2.bind(this)}/>
                </div>
            </div>
        )
    }

}
export default Employee
